package cvi.com.reader.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.heima.tabview.library.TabView;
import com.heima.tabview.library.TabViewChild;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.hawk.Hawk;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.CollcetDisplayDataListener;
import cvi.com.reader.bean.DeleteAllCollcetDataListener;
import cvi.com.reader.bean.DeleteAllDraftDataListener;
import cvi.com.reader.bean.DeleteAllPubilcDataListener;
import cvi.com.reader.bean.DraftDisplayDataListener;
import cvi.com.reader.bean.LoginBean;
import cvi.com.reader.bean.LonginBeanNew;
import cvi.com.reader.bean.PublicDisplayListnener;
import cvi.com.reader.bean.constant;
import cvi.com.reader.fragment.PersonalCollectFragment;
import cvi.com.reader.fragment.PersonalDraftsFragment;
import cvi.com.reader.fragment.PersonalFragment;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.UtilsOnclickListen;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/7/29.
 * <p>
 * 个人中心
 */

public class PersonalActivity extends BaseActivity implements View.OnClickListener, DraftDisplayDataListener, PublicDisplayListnener, CollcetDisplayDataListener {
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.imageview)
    CircleImageView imageview;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.header)
    RelativeLayout header;
    @BindView(R.id.tabView)
    TabView tabView;
    @BindView(R.id.delete_all)
    LinearLayout deleteAll;
    @BindView(R.id.right_icon)
    LinearLayout rightIcon;
    @BindView(R.id.right_ll)
    LinearLayout rightLl;
    private PersonalFragment personalFragment1 = null;
    private PersonalDraftsFragment personalFragment2 = null;
    private PersonalCollectFragment personalFragment3 = null;
    private LonginBeanNew loginBean = null;
    private String currentFragmentFlag = "1";
    private DeleteAllPubilcDataListener deleteAllPubilcDataListener;
    private DeleteAllDraftDataListener deleteAllDraftDataListener;
    private DeleteAllCollcetDataListener deleteAllCollcetDataListener;
    private boolean isLoginOut = false;
    private boolean pulicDisplay = false;
    private boolean draftDisplay = false;
    private boolean collcetDiplay = false;
    private MyReceiver myReceiver;
    private int like_num;//点赞数
    private int pubilc_num;//作品数
    private DialogPlus outDialog;

    public DeleteAllDraftDataListener getDeleteAllDraftDataListener() {
        return deleteAllDraftDataListener;
    }

    public void setDeleteAllDraftDataListener(DeleteAllDraftDataListener deleteAllDraftDataListener) {
        this.deleteAllDraftDataListener = deleteAllDraftDataListener;
    }

    public DeleteAllCollcetDataListener getDeleteAllCollcetDataListener() {
        return deleteAllCollcetDataListener;
    }

    public void setDeleteAllCollcetDataListener(DeleteAllCollcetDataListener deleteAllCollcetDataListener) {
        this.deleteAllCollcetDataListener = deleteAllCollcetDataListener;
    }

    public DeleteAllPubilcDataListener getDeleteAllPubilcDataListener() {
        return deleteAllPubilcDataListener;
    }

    public void setDeleteAllPubilcDataListener(DeleteAllPubilcDataListener deleteAllPubilcDataListener) {
        this.deleteAllPubilcDataListener = deleteAllPubilcDataListener;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal;
    }

    @Override
    protected void initView() {
        rightIcon.setVisibility(View.VISIBLE);
        rightIcon.setOnClickListener(this);

        if (Hawk.contains("longinBeanNew")) {
            loginBean = Hawk.get("longinBeanNew");
            name.setText(loginBean.getMsg().getRealname());
       /*     String strUrl = null;
            if (Hawk.contains("ip")) {
                strUrl = Hawk.get("ip");
            }
            if (strUrl != null) {

            }*/
            Glide.with(PersonalActivity.this).load("http://" + constant.URL + loginBean.getMsg().getAvatar()).into(imageview);
        }
        back.setOnClickListener(this);
        tittle.setText("个人中心");
        deleteAll.setOnClickListener(this);
        rightLl.setOnClickListener(this);
        deleteAll.getBackground().setAlpha(200);
        personalFragment1 = new PersonalFragment();
        personalFragment2 = new PersonalDraftsFragment();
        personalFragment3 = new PersonalCollectFragment();
        List<TabViewChild> tabViewChildList = new ArrayList<>();
        TabViewChild tabViewChild01 = new TabViewChild(R.mipmap.selete_tab_my_publish, R.mipmap.unselete_tab_my_publish, "我的发布", personalFragment1);
        TabViewChild tabViewChild02 = new TabViewChild(R.mipmap.selete_tab_drafts, R.mipmap.unselete_tab_drafts, "草稿箱", personalFragment2);
        TabViewChild tabViewChild03 = new TabViewChild(R.mipmap.selete_tab_my_collect, R.mipmap.unselete_tab_my_collect, "我的收藏", personalFragment3);
        tabViewChildList.add(tabViewChild01);
        tabViewChildList.add(tabViewChild02);
        tabViewChildList.add(tabViewChild03);
        tabView.setTabViewDefaultPosition(0);
        tabView.setTabViewChild(tabViewChildList, getSupportFragmentManager());
        Bundle bundle = new Bundle();
        bundle.putString("type", "1");
        personalFragment1.setArguments(bundle);
        tabView.setOnTabChildClickListener(new TabView.OnTabChildClickListener() {
            @Override
            public void onTabChildClick(int position, ImageView currentImageIcon, TextView currentTextView) {
                // currentTextView.setBackgroundResource(R.drawable.login_background_selector);
                if ("我的发布".equals(currentTextView.getText().toString().trim())) {
                    Bundle bundle = new Bundle();
                    bundle.putString("type", "1");
                    personalFragment1.setArguments(bundle);
                    currentFragmentFlag = "1";
                    if (pulicDisplay) {
                        deleteAll.setVisibility(View.GONE);
                    } else {
                        deleteAll.setVisibility(View.VISIBLE);
                    }
                } else if ("草稿箱".equals(currentTextView.getText().toString().trim())) {
                    Bundle bundle = new Bundle();
                    bundle.putString("type", "2");
                    personalFragment2.setArguments(bundle);
                    currentFragmentFlag = "2";
                    if (draftDisplay) {
                        deleteAll.setVisibility(View.GONE);
                    } else {
                        deleteAll.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (collcetDiplay) {
                        deleteAll.setVisibility(View.GONE);
                    } else {
                        deleteAll.setVisibility(View.VISIBLE);
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("type", "3");
                    personalFragment3.setArguments(bundle);
                    currentFragmentFlag = "3";
                }
            }
        });
        LinearLayout linearLayout = (LinearLayout) tabView.getChildAt(0);

        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);

        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.bg_line));

        linearLayout.setDividerPadding(20);

    }

    @Override
    protected void initData() {
        getLikes();
        getWorks();


    }

    //点赞数
    private void getLikes() {
        NetWorkManager.getInstance().getNetWorkApiService().getLikes().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PersonalActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        like_num = 0;
                        like_num = response.getIntValue("msg");
                        num.setText("作品：" + pubilc_num);
                        Log.d("xsddd", like_num + "    =" + like_num + "     response=" + response.getIntValue("msg") + "    " + response.getString("msg"));
                    }
                });
    }

    //作品数
    private void getWorks() {
        NetWorkManager.getInstance().getNetWorkApiService().getWorks().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PersonalActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        pubilc_num = 0;
                        pubilc_num = response.getIntValue("msg");
                        num.setText("作品：" + pubilc_num + "     共获赞：" + like_num);
                        Log.d("xsddd", pubilc_num + "    =" + pubilc_num + "     response=" + response.getIntValue("msg") + "    " + response.getString("msg"));

                    }
                });
    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.delete_all:
                if ("1".equals(currentFragmentFlag)) {
                    deleteAllPubilcDataListener.onDEleteAll("1");
                } else if ("2".equals(currentFragmentFlag)) {
                    deleteAllDraftDataListener.onDEleteAll("2");
                } else {
                    deleteAllCollcetDataListener.onDEleteAll("3");
                }
                break;
            case R.id.right_icon:
                if (UtilsOnclickListen.isFastClick()) {
                    showDialog();
                }
                break;
            case R.id.right_ll:
                if (UtilsOnclickListen.isFastClick()) {
                    jump(PartyMemberInfoActivity.class);
                }
                break;
        }
    }

    private void loginOut() {

        NetWorkManager.getInstance().getNetWorkApiService().loginOut().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PersonalActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(PersonalActivity.this, "退出成功！", Toast.LENGTH_LONG).show();
                        jump(LoginActivityNew.class);
                        isLoginOut = true;
                        finish();
                    }
                });
    }

    private void showDialog() {
        View view = LayoutInflater.from(PersonalActivity.this).inflate(R.layout.dialog_delete, null);
        Button confirm = view.findViewById(R.id.confir_btn);
        Button cancel = view.findViewById(R.id.cancel_btn);
        TextView tv = view.findViewById(R.id.tips);
        tv.setText("确定要退出账号吗？ ");
        outDialog = DialogPlus.newDialog(PersonalActivity.this)
                .setContentHolder(new ViewHolder(view))
                .setCancelable(true)
                .setGravity(Gravity.CENTER)
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogPlus dialog) {

                    }
                }).create();
        outDialog.show();
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UtilsOnclickListen.isFastClick()) {
                    loginOut();
                    outDialog.dismiss();
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                outDialog.dismiss();
            }
        });
    }

    @Override
    public void onPublicDisplay(String flag) {
        Log.d("sddddd", "我的发布");
        if ("0".equals(flag)) {
            pulicDisplay = true;
            deleteAll.setVisibility(View.GONE);

        } else {
            pulicDisplay = false;
            // deleteAll.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onDraftDisplay(String flag) {
        Log.d("sddddd", "我的草稿箱");
        if ("0".equals(flag)) {
            draftDisplay = true;
            deleteAll.setVisibility(View.GONE);
        } else {
            draftDisplay = false;
            //deleteAll.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onCollcetDisplay(String flag) {
        Log.d("sddddd", "我的收藏");
        if ("0".equals(flag)) {
            collcetDiplay = true;
            deleteAll.setVisibility(View.GONE);
        } else {
            collcetDiplay = false;
            // deleteAll.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        //注册广播接收器
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(constant.PERSONAL_MYRECEIVER);
        registerReceiver(myReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            initData();
        }
    }
}
